package com.hjq.fcloud.widget

import android.content.Context
import android.text.InputFilter
import android.util.AttributeSet
import android.widget.EditText
import android.widget.LinearLayout
import com.hjq.fcloud.R
import com.hjq.fcloud.ktx.ViewKtx.setVisibility
import com.jakewharton.rxbinding.widget.RxTextView
import kotlinx.android.synthetic.main.layout_common_input.view.inputNumberTv
import kotlinx.android.synthetic.main.layout_common_input.view.inputView
import kotlinx.android.synthetic.main.layout_common_input.view.replyEt
import kotlinx.android.synthetic.main.layout_common_input.view.replyTv


/**
 * 公共输入控件
 */
class CommonInPutView : LinearLayout {

    private var maxLength: Int? = null
    private var hint: String? = null

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        parseTypedArray(context, attrs)

        inflateView()

        setViewData()
    }

    private fun setViewData() {
        hint?.let {
            replyEt.setHint(hint)
        }
        maxLength?.let {
            val filters = arrayOfNulls<InputFilter>(1)
            filters[0] = InputFilter.LengthFilter(it)
            replyEt.setFilters(filters)
        }

        inputNumberTv.setText("")
        RxTextView.textChanges(replyEt).subscribe {
            inputNumberTv.setText(it.length.toString().plus("/").plus(maxLength))
        }
    }

    private fun parseTypedArray(context: Context?, attrs: AttributeSet?) {
        val typedArray = context!!.obtainStyledAttributes(
            attrs,
            R.styleable.CommonInPutView
        )
        maxLength = typedArray.getInteger(
            R.styleable.CommonInPutView_max_number,
            1000
        )
        hint = typedArray.getString(
            R.styleable.CommonInPutView_hint
        )
        typedArray.recycle()
    }

    private fun inflateView() {
        inflate(context, R.layout.layout_common_input, this)
    }

    fun setEnable(enable:Boolean){
        replyEt.isEnabled = enable
    }

    open fun getInPutText(): String {
        return replyEt.text.toString()
    }

    open fun getInPutView(): EditText {
        return replyEt
    }


    open fun setInPutText(text: String?,isEdit:Boolean? = false) {
        if(isEdit == true){
            inputView.setVisibility(true)
            replyEt.setText(text)

            replyTv.setVisibility(false)
        }else{
            inputView.setVisibility(false)
            replyTv.setVisibility(true)
            replyTv.setText(text)
        }
    }

    open fun getInPutHintText(): String {
        return replyEt.hint.toString()
    }

}